<template>
  <div class="resource-view">
    <el-button @click="fetchData('select')">访问资源1</el-button>
    <el-button @click="fetchData('update')">访问资源2</el-button>
  </div>
  <div v-if="data" class="data-display">
    <pre>{{ data }}</pre>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';

const data = ref('');

const fetchData = async (method) => {
  try {
    const url = `http://localhost:8080/api/${method}`;
    //从localStorage中获取登录成功后存储的jwt令牌
    const token = localStorage.getItem('token');
    //向服务器发送请求时携带jwt令牌，headers: { "Authorization": `Bearer ${token}` }
    const response = await axios({
      method: method === 'select' ? 'GET' : 'PUT',
      url,
      headers: { "Authorization": `Bearer ${token}` },
      data: method === 'update' ? {} : undefined
    });

    if (response.data.code === 200) {
      ElMessage.success(response.data.message);
      data.value = response.data.data;
    } else {
      ElMessage.error(response.data.message || '操作失败');
    }
  } catch (error) {
    ElMessage.error('请求失败，请检查网络或服务器状态');
    console.error(error);
  }
};
</script>

<style scoped>
.resource-view {
  padding: 20px;
}

.data-display {
  margin-top: 20px;
  background-color: #f5f5f5;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}
</style>

<style scoped>
.resource-view {
  padding: 20px;
}
</style>